﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.SelfHost;
using Tile_Generator;

namespace TileWindowsService
{
    public partial class HttpApiService : ServiceBase
    {

        private HttpSelfHostServer _server;
        private readonly HttpSelfHostConfiguration _config;
        public const string ServiceAddress = "http://localhost:2345";

        public HttpApiService()
        {

            _config = new HttpSelfHostConfiguration(ServiceAddress);
            _config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}",
                new { id = RouteParameter.Optional });

            _config.Formatters.RemoveAt(0);

          

        }

        protected override void OnStart(string[] args)
        {
            _server = new HttpSelfHostServer(_config);
            _server.OpenAsync().Wait();
        }

        protected override void OnStop()
        {
            _server.CloseAsync().Wait();
            _server.Dispose();
        }
    }

    public class TileUpdaterController : ApiController
    {
        public HttpResponseMessage Get(int position)
        {
            var msg = string.Format("Received request for position {0}", position);
            Console.WriteLine(msg);

            var tileTitle = string.Format("Notification {0} /n Comments", position);
            var number = position.ToString();
            var tilesSubtitle = DateTime.Now;

            var result = Generator.Generate(tileTitle, tilesSubtitle, number);

            var response = Request.CreateResponse(HttpStatusCode.OK, result);
            response.Headers.Add("X-WNS-Expires", tilesSubtitle.AddMinutes(0.25).ToString("r"));
            response.Headers.Add("X-WNS-Tag", position.ToString());

            return response;
        }

    }
}
